package com.talent.core.protocol.mqtt.handler;

import com.talent.core.protocol.mqtt.config.Constant;
import com.talent.core.protocol.mqtt.enums.TlMqttMessageType;
import com.talent.core.protocol.mqtt.model.fix.TlMqttFixedHead;
import com.talent.core.protocol.mqtt.model.request.TlMqttPubRecReq;
import com.talent.core.protocol.mqtt.model.response.TlMqttPubRec;
import com.talent.core.protocol.mqtt.model.variable.TlMqttPubRecVariableHead;
import com.talent.core.protocol.mqtt.store.IMqttStore;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;


/**
 * @ClassName：TlMqttRecHandler
 * @Author: hszhou
 * @Date: 2024/12/5 9:46
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@ChannelHandler.Sharable
public class TlMqttPubRecHandler extends SimpleChannelInboundHandler<TlMqttPubRecReq> {

    private static final Logger logger = LoggerFactory.getLogger(TlMqttPubRecHandler.class);

    private IMqttStore mqttStore;

    public TlMqttPubRecHandler(IMqttStore mqttStore){
        this.mqttStore = mqttStore;
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TlMqttPubRecReq req) throws Exception {
        logger.debug("进入【PUBREC】处理器");
        //本地删除这个消息
        TlMqttPubRecVariableHead vh = req.getVariableHead();
        Integer messageId = vh.getMessageId();
        mqttStore.removeStoreMsg(messageId);
        mqttStore.storePubRec(messageId,req);
        //发送REL消息 删除本地的消息
        TlMqttFixedHead head = new TlMqttFixedHead();
        head.setMessageType(TlMqttMessageType.PUBREL.getValue());
        head.setLength(Constant.SHORT_LENGTH);
        TlMqttPubRecVariableHead variableHead = new TlMqttPubRecVariableHead();
        variableHead.setMessageId(req.getVariableHead().getMessageId());
        TlMqttPubRec res = new TlMqttPubRec(head,variableHead);
        res.setFixedHead(head);
        res.setVariableHead(variableHead);
        ctx.channel().writeAndFlush(res);
        Object clientId = ctx.channel().attr(AttributeKey.valueOf(Constant.CLIENT_ID)).get();
        logger.debug("客户端【{}】构建【PUBREL】消息返回【{}】",clientId,res);

        //说明没收到pubComp的包 还需要挨次发送rec的
        ctx.channel().eventLoop().schedule(()->{
            TlMqttPubRecReq pubRec = mqttStore.getPubRec(messageId);
            if(pubRec!=null){
                if (ctx != null) {
                    ctx.channel().writeAndFlush(res);
                }
            }
        },1, TimeUnit.MINUTES);

    }
}
